/*
 * @Author: ૮₍ ˙О˙₎ა
 * @Date: 2023-07-12 18:19:45
 */
import axios, { type Method } from 'axios'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { removeToken } from './token-utils'
import router from '@/router'
import { showToast } from 'vant'
// 创建axios实例
const instance = axios.create({
  baseURL: '/yx',
  timeout: 5000
})

// 添加请求拦截器
instance.interceptors.request.use(
  (config) => {
    NProgress.start()
    return config
  },
  (error) => {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

// 添加响应拦截器
instance.interceptors.response.use(
  (response) => {
    // 简化响应数据
    const res = response.data
    // console.log(response)
    NProgress.done()
    return res
  },
  (error) => {
    // console.log()
    NProgress.done()

    return Promise.reject(error)
  }
)

export interface IReqDataRes<T> {
  [x: string]: any
  code: number
  data: T
  message: string
  success: boolean
}

/**
 * @description: 二次封装axios请求
 * @return {*}
 * @param {*} T
 */
const httpYX = <T>(url: string, method: Method, data?: unknown) => {
  const newMeThod = method.toLocaleUpperCase()
  return instance.request<IReqDataRes<T>, IReqDataRes<T>>({
    url,
    method: newMeThod,
    params: newMeThod === 'GET' ? data : {},
    data: newMeThod === 'POST' || newMeThod === 'PUT' || newMeThod === 'DELETE' ? data : {}
  })
}

export { httpYX, instance }
